package com.nycreativity.elecreativity.controller


import com.baomidou.mybatisplus.core.toolkit.IdWorker
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.nycreativity.elecreativity.entity.ResultData
import com.nycreativity.elecreativity.entity.cons.CommonURLConstants
import com.nycreativity.elecreativity.entity.enums.IsDelEnum
import com.nycreativity.elecreativity.entity.param.PageParam
import com.nycreativity.elecreativity.entity.po.Favorite
import com.nycreativity.elecreativity.entity.vo.favorite.FavoriteVO
import com.nycreativity.elecreativity.entity.vo.PageDataVO
import com.nycreativity.elecreativity.service.FavoriteService
import com.nycreativity.elecreativity.util.usersession.UserContext
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime

import javax.annotation.Resource

/**
 * <p>
 *  我的收藏前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-03-11
 */
@RestController
@RequestMapping(CommonURLConstants.FAVORITE_PREFIX)
@Api(tags = ["收藏相关接口"])
class FavoriteController {

    @Resource
    lateinit var favoriteService: FavoriteService

    @PostMapping("{skuId}")
    @ApiOperation("添加商品收藏")
    fun addFavorite(@PathVariable("skuId") skuId: Long): ResultData<Boolean> {
        val loginUser = UserContext.get()
        return if (
            loginUser != null &&
            favoriteService.save(
                Favorite(IdWorker.getId(), loginUser.id, skuId)
                    .apply {
                        createTime = LocalDateTime.now()
                        creator = loginUser.id
                    }
            )
        ) ResultData.SUCCESS("收藏添加成功")
        else ResultData.FAILED("收藏添加失败")
    }

    @GetMapping()
    @ApiOperation("获取商品收藏")
    fun getFavorite(pageParam: PageParam): ResultData<PageDataVO<FavoriteVO>> {
        return ResultData.SUCCESS(data = favoriteService.queryFavorites(pageParam))
    }

    @DeleteMapping("{id}")
    @ApiOperation("删除商品收藏")
    fun removeFavorite(@PathVariable("id") id: Long): ResultData<Boolean> {
        val loginUser = UserContext.get()
        val favorite = Favorite(id, loginUser.id)
        favorite.modify()
        val wrapper = KtQueryWrapper(Favorite::class.java)
            .eq(Favorite::id, id)
            .eq(Favorite::userId, loginUser.id)
        return if (
            loginUser != null &&
            favoriteService.update(favorite, wrapper) && favoriteService.remove(wrapper)
        ) ResultData.SUCCESS("收藏删除成功")
        else ResultData.FAILED("收藏删除失败")
    }

}

